package cn.lili.mybatis.mybatisplus;

import cn.lili.common.utils.SpringContextUtil;
import cn.lili.exchange.AmqpExchangeProperties;
import cn.lili.routing.GoodsRoutingKey;
import cn.lili.util.AmqpMessage;
import cn.lili.util.AmqpSender;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import com.baomidou.mybatisplus.extension.parser.JsqlParserSupport;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.ParameterMapping;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Connection;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

@Slf4j
@Service
public class GoodsInterceptor extends JsqlParserSupport implements InnerInterceptor {


    @Override
    public void beforePrepare(StatementHandler sh, Connection connection, Integer transactionTimeout) {
        PluginUtils.MPStatementHandler mpSh = PluginUtils.mpStatementHandler(sh);
        PluginUtils.MPBoundSql mpBs = mpSh.mPBoundSql();

        String sql = mpBs.sql();
        //log.error("ssssssssssss == {}", sql);
        sql = sql.toLowerCase();
        if (!sql.contains("li_goods") && !sql.contains("li_goods_sku")) {
            return;
        }
        if (sql.contains("select ")) {
            return;
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("sql", sql);
        boolean insert = sql.contains("insert ");
        if (insert) {
            jsonObject.put("goods_type","goods.insert");
        }
        boolean update = sql.contains("update ");
        if (update) {
            jsonObject.put("goods_type","goods.update");
        }
        boolean delete = sql.contains("delete ");
        if (delete) {
            jsonObject.put("goods_type","goods.delete");
        }
        AmqpTemplate amqpTemplate = SpringContextUtil.getBean(RabbitTemplate.class);
        amqpTemplate.convertAndSend("goods_lilishop",GoodsRoutingKey.GOODS_CHANGE, jsonObject.toJSONString());
    }


}